package javabase.concurrent;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheDemo<V> {

	
	private ConcurrentHashMap<String, V> map = new ConcurrentHashMap<>();
	private ReadWriteLock lock = new ReentrantReadWriteLock();
	
	public V get(String key) {
		lock.readLock().lock();
		try {
			V v =  map.get(key);
			if (v == null) {
				lock.readLock().unlock();
				lock.writeLock().lock();
				try {
					if (v == null) {
						v = (V) new Object();
					}
				} finally {
					lock.writeLock().unlock();
				}
				lock.readLock().lock();
			}
			return v;
		} finally {
			lock.readLock().unlock();
		}
	}
	
	
}
